//
//  ReadFile.m
//  ReadFile
//
//  Created by CRY on 16/7/26.
//  Copyright © 2016年 EGOVA. All rights reserved.
//

#import "ReadFile.h"

@interface ReadFile()

@property (nonatomic, strong) NSFileManager *fileManager;
@property (nonatomic, copy  ) NSString      *inputPath;
@property (nonatomic, copy  ) NSString      *outputPath;
@property (nonatomic, strong) NSArray       *fileTypes;

@end

@implementation ReadFile


+ (void)readFileWithPath:(NSString *)path
               fileTypes:(NSArray *)fileTypes
              outputPath:(NSString *)outputPath;{
    
    ReadFile *readFile =[[ReadFile alloc] initWithFileTypes:fileTypes
                                                  inputPath:path
                                                 outputPath:outputPath];
    [readFile drawFileWithPath:path];
    NSLog(@"操作完成！");
}

- (instancetype)initWithFileTypes:(NSArray *)fileTypes
                        inputPath:(NSString *)inputPath
                       outputPath:(NSString *)outputPath{
    
    if (self = [super init]) {
        
        _fileManager = [NSFileManager defaultManager];
        _fileTypes   = fileTypes;
        _inputPath   = inputPath;
        _outputPath  = outputPath;
    }
    return self;
}

- (void)drawFileWithPath:(NSString *)path{
    
    NSArray *fileArray = [_fileManager contentsOfDirectoryAtPath:path error:nil];
    for (NSString *fileName in fileArray) {
        
        BOOL isDirectory;
        NSString *filePath = [path stringByAppendingPathComponent:fileName];
        [_fileManager fileExistsAtPath:filePath
                           isDirectory:&isDirectory];
        
        if (isDirectory) {
            [self drawFileWithPath:filePath];
        }else{
            [self judgeFileTypeWithPath:filePath
                               fileName:fileName];
        }
    }
}

- (void)judgeFileTypeWithPath:(NSString *)path
                     fileName:(NSString *)fileName{
    
    for (NSString *fileType in _fileTypes) {
        
        if ([fileType isEqualToString:[fileName pathExtension]]) {
            
            NSString *outputPath = [_outputPath stringByAppendingString:[path substringWithRange:NSMakeRange(_inputPath.length, path.length - _inputPath.length - fileName.length)]];
            // 创建目标文件夹
            if ([_fileManager fileExistsAtPath:outputPath] == NO) {
                [_fileManager createDirectoryAtPath:outputPath
                        withIntermediateDirectories:YES
                                         attributes:nil
                                              error:nil];
            }
            // 拷贝目标文件
            [_fileManager copyItemAtPath:path
                                  toPath:[outputPath stringByAppendingPathComponent:fileName]
                                   error:nil];
        }
    }
}

@end
